package com.bwie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.mapper.UserMapper;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
* @author 36167
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-03-06 09:14:40
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    UserMapper userMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public R login(LoginInfoVo loginInfoVo) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,loginInfoVo.getUserName());
        wrapper.eq(User::getUserPass,loginInfoVo.getUserPass());
        User one = getOne(wrapper);
        if (one==null){
            throw new RuntimeException("用户不存在");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123465")
                .claim("uid", one.getUid()).claim("username", one.getUserName()).compact();
        stringRedisTemplate.opsForValue().set(one.getUserName(),token);
        HashMap<String, Object> map = new HashMap<>();
        map.put("user",one);
        map.put("token",token);
        return R.ok(map);
    }

    @Override
    public User show(Integer uid) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUid,uid);

        return getOne(wrapper);
    }

    @Override
    public R del(Integer uid) {
        int i = userMapper.deleteById(uid);
        return i>0?R.ok("删除成功"):R.failed("删除失败");
    }

    @Override
    public R submit(User user) {
        User user1 = new User();
        BeanUtil.copyProperties(user,user1);
        if (user1.getUid()==null){
            userMapper.insert(user);
        }else {
            userMapper.updateById(user);
        }
        log.info("uid:{}",user1.getUid());
        User user2 = userMapper.selectById(user1.getUid());
        return R.ok(user2);
    }
}




